package com.autumn.mybatis.provider.mysql;

/**
 * MySql 帮助
 * 
 * @author 老码农
 *
 *         2017-10-29 14:22:45
 */
public class MySqlUtils {

	/**
	 * 创建 Section 的 Where Sql
	 * 
	 * @param section
	 *            段名称
	 * @return
	 */
	public static String createSectionWhereSql(String section) {
		StringBuilder sql = new StringBuilder();
		sql.append("<where>");
		sql.append("<trim prefix=\"(\" suffix=\")\" prefixOverrides=\"AND|OR|NOT\">");
		sql.append("<foreach collection=\"" + section + ".criterias\" item=\"criteria\" >");
		sql.append(createCriterion("criteria"));
		sql.append("</foreach>");
		sql.append("</trim>");
		sql.append("</where>");
		return sql.toString();
	}

	private static String createCriterion(String criteriaName) {
		StringBuilder sql = new StringBuilder();
		sql.append("<choose>");
		sql.append(String.format("<when test=\"%1$s.op == 'LIKE'\">", criteriaName));
		sql.append(createCriterionItem(criteriaName, "LIKE CONCAT('%',#{" + criteriaName + ".value},'%' )"));
		sql.append("</when>");
		sql.append(String.format("<when test=\"%1$s.op == 'LEFT_LIKE'\">", criteriaName));
		sql.append(createCriterionItem(criteriaName, "LIKE CONCAT(#{" + criteriaName + ".value},'%' )"));
		sql.append("</when>");
		sql.append(String.format("<when test=\"%1$s.op == 'RIGHT_LIKE'\">", criteriaName));
		sql.append(createCriterionItem(criteriaName, "LIKE CONCAT('%',#{" + criteriaName + ".value})"));
		sql.append("</when>");
		sql.append(String.format("<when test=\"%1$s.op == 'BETWEEN'\">", criteriaName));
		sql.append(createCriterionItem(criteriaName,
				"BETWEEN #{" + criteriaName + ".value} AND  #{" + criteriaName + ".secondValue} "));
		sql.append("</when>");
		sql.append("<otherwise>");
		sql.append(createCriterionItem(criteriaName, "${" + criteriaName + ".op} #{" + criteriaName + ".value}"));
		sql.append("</otherwise>");
		sql.append("</choose>");
		return sql.toString();
	}

	private static String createCriterionItem(String criteriaName, String content) {
		StringBuilder sql = new StringBuilder();
		sql.append(" ${");
		sql.append(criteriaName);
		sql.append(".logic} ${");
		sql.append(criteriaName);
		sql.append(".leftBrackets}${");
		sql.append(criteriaName);
		sql.append(".expression} ");
		sql.append(content);
		sql.append("${");
		sql.append(criteriaName);
		sql.append(".rigthBrackets}");
		return sql.toString();
	}

}
